package com.syni.mdd.yhd.common.all.service.impl.activity;

import com.syni.mdd.sjb.common.component.utils.common.utils.ArithUtil;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.activity.BmsBackCardDao;
import com.syni.mdd.yhd.common.all.entity.activity.BmsBackCard;
import com.syni.mdd.yhd.common.all.entity.activity.BmsDrLogic;
import com.syni.mdd.yhd.common.all.entity.activity.BmsDrOrderLog;
import com.syni.mdd.yhd.common.all.service.activity.BmsBackCardService;
import com.syni.mdd.yhd.common.all.service.activity.BmsDrLogicService;
import com.syni.mdd.yhd.common.all.service.activity.BmsDrOrderLogService;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.yhd.common.all.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @className
 * @description TOO
 * @Author hwq
 * @DATE 2019/9/23 10:34
 * @VERSION 1.0
 **/
@Service
public class BmsBackCardServiceImpl extends BaseService<BmsBackCard, Integer> implements BmsBackCardService {

    //返现卡到期时间
    private final String EXPIRE_TIME = "2020-10-01";

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    BmsBackCardDao bmsBackCardDao;

    @Autowired
    BmsDrLogicService bmsDrLogicService;

    @Autowired
    BmsDrOrderLogService bmsDrOrderLogService;

    @Override
    public BmsBackCardDao getBaseDao() {
        return bmsBackCardDao;
    }

    @Override
    public Map<String, Object> getMyBackCard(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("isOpen",Constants.COMMON_FLAG_TRUE_INT);
        List<BmsBackCard> bmsBackCards = bmsBackCardDao.findAll(new SpecificationUtils(conditionMap));
        BmsBackCard bmsBackCard;
        if(!(bmsBackCards != null && bmsBackCards.size() > 0)){
            //新增一个返现卡
            bmsBackCard = new BmsBackCard();
            bmsBackCard.setUserId(userId);
            bmsBackCard.setTotal(0d);
            bmsBackCard.setNewTime(new Date());
            bmsBackCard.setIsOpen(Constants.COMMON_FLAG_TRUE_INT);
            bmsBackCard.setExpireTime(DateTimeUtils.addDay(DateTimeUtils.converStringToDate(EXPIRE_TIME),1));
            bmsBackCardDao.save(bmsBackCard);
            bmsBackCards.add(bmsBackCard);
        }else {
            bmsBackCard = bmsBackCards.get(0);
        }
        /*if(checkBackCardExpireTime(bmsBackCard)){
            return ResultMapHelper.success(null,ResultMsg.MSG_GET_SUCCESS);
        }*/
        return ResultMapHelper.success(bmsBackCard,ResultMsg.MSG_GET_SUCCESS);
    }

    public boolean checkBackCardExpireTime(BmsBackCard bmsBackCards){
        Integer nowTime = DateTimeUtils.getNowTimeStamp();
        return nowTime >= DateTimeUtils.converDateToInterger(bmsBackCards.getExpireTime());
    }

    @Override
    public Map<String, Object> openBackCardActivity(ParamsMap paramsMap) {
        Integer userId = null;
        Map<String,Object> checkRet = RequestParamUtils.checkAuthor(paramsMap);
        if(checkRet.containsKey("status") && ResultCode.CODE_NORMAL.equals(checkRet.get("status").toString())){
            userId = paramsMap.getInteger("userIdentify");
        }
        Integer nowTime = DateTimeUtils.getNowTimeStamp();
        if(redisTemplate.hasKey(Constants.REDIS_KEY_FULL_BACK_CARD_OPEN)){
            String activityTime = redisTemplate.opsForValue().get(Constants.REDIS_KEY_FULL_BACK_CARD_OPEN).toString();
            String[] startEndTime = activityTime.split(",");
            Integer startTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate(startEndTime[0],DateTimeUtils.DATE_PATTERN_DAY_07));
            Integer endTime = DateTimeUtils.converDateToInterger(DateTimeUtils.addDay(DateTimeUtils.converStringToDate(startEndTime[1],DateTimeUtils.DATE_PATTERN_DAY_07),1));
            if(nowTime >= startTime && nowTime < endTime) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("startTime", startEndTime[0]);
                resultMap.put("endTime", startEndTime[1]);
                return ResultMapHelper.success(resultMap, "ok");
            }else if(userId != null){
                List<BmsDrLogic> bmsDrLogics = bmsDrLogicService.getUserTask(userId);
                if(bmsDrLogics != null && bmsDrLogics.size() > 0){
                    BmsDrLogic bmsDrLogic = bmsDrLogics.get(0);
                    if(bmsDrLogic.getCompleteNum() < 5 && bmsDrLogic.getExpireTime() != null){
                        if(DateTimeUtils.converDateToInterger(bmsDrLogic.getExpireTime()) > nowTime){
                            Map<String, Object> resultMap = new HashMap<>();
                            resultMap.put("startTime", startEndTime[0]);
                            resultMap.put("endTime", DateTimeUtils.converDateToString(bmsDrLogic.getExpireTime(),DateTimeUtils.DATE_PATTERN_DAY_09));
                            return ResultMapHelper.success(resultMap, "ok");
                        }
                    }
                }
            }
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR,"no activity");
    }

    @Override
    @Transactional
    public Map<String, Object> withdrawal(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer drLogicId = paramsMap.getInteger("drLogicId");
        List<BmsDrLogic> bmsDrLogics = bmsDrLogicService.getUserTask(userId);
        if(!(bmsDrLogics != null && bmsDrLogics.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_BACK_NO_HAVING,ResultMsg.CODE_ORDER_BACK_NO_HAVING);
        }
        BmsDrLogic bmsDrLogic = bmsDrLogics.get(0);
        if(bmsDrLogic.getCompleteNum() < 5){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_BACK_NO_HAVING,ResultMsg.CODE_ORDER_BACK_NO_HAVING);
        }
        BmsBackCard bmsBackCard = withdrawalHandle(userId,bmsDrLogic);
        return ResultMapHelper.success(bmsBackCard,ResultMsg.HAND_SUCCESS);
    }




    public BmsBackCard withdrawalHandle(Integer userId,BmsDrLogic bmsDrLogic) {
        //随机返现
        List<BmsDrOrderLog> bmsDrOrderLogs = bmsDrOrderLogService.getBaseDao().findByDrLogicId(bmsDrLogic.getId());
        Double backMoney = 0d;
        for(BmsDrOrderLog bmsDrOrderLog : bmsDrOrderLogs){
            if(backMoney == 0d){
                backMoney = bmsDrOrderLog.getBackMoney();
            }
            if(backMoney > bmsDrOrderLog.getBackMoney()){
                backMoney = bmsDrOrderLog.getBackMoney();
            }
        }
        /*do {
            int random = (int)(Math.random() * bmsDrOrderLogs.size());
            BmsDrOrderLog bmsDrOrderLog = bmsDrOrderLogs.get(random);
            if(bmsDrOrderLog.getBackMoney() > 0d){
                backMoney = bmsDrOrderLog.getBackMoney();
            }
            bmsDrOrderLogs.remove(random);
            if(bmsDrOrderLogs.size() == 0){
                break;
            }
        }
        while (backMoney == 0d);*/
        //开始返现
        BmsBackCard bmsBackCard = bmsBackCardDao.findByUserId(userId);
        if(bmsBackCard == null){
            bmsBackCard = new BmsBackCard();
            bmsBackCard.setUserId(userId);
            bmsBackCard.setTotal(0d);
            bmsBackCard.setNewTime(new Date());
            bmsBackCard.setExpireTime(DateTimeUtils.addDay(DateTimeUtils.converStringToDate(EXPIRE_TIME),1));
            bmsBackCard.setIsOpen(Constants.COMMON_FLAG_TRUE_INT);
        }
        bmsBackCard.setTotal(ArithUtil.add(bmsBackCard.getTotal(),backMoney));
        if(bmsBackCard.getTotal() > 500d){
            bmsBackCard.setTotal(500d);
        }
        bmsBackCardDao.save(bmsBackCard);
        bmsDrLogic.setStatus(Constants.ALREADY_GET);
        bmsDrLogicService.getBaseDao().save(bmsDrLogic);
        return bmsBackCard;
    }

    @Override
    public Map<String, Object> getMyBackCardTask(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        List<BmsDrLogic> bmsDrLogics = bmsDrLogicService.getUserTask(userId);
        if(bmsDrLogics != null && bmsDrLogics.size() > 0){
            //找出订单日志记录
            BmsDrLogic bmsDrLogic = bmsDrLogics.get(0);
            List<BmsDrOrderLog> bmsDrOrderLogs = bmsDrOrderLogService.getBaseDao().findByDrLogicId(bmsDrLogic.getId());
            bmsDrLogic.setBmsDrOrderLogList(bmsDrOrderLogs);
            return ResultMapHelper.success(bmsDrLogic,ResultMsg.MSG_GET_SUCCESS);
        }
        return ResultMapHelper.success(null,ResultMsg.MSG_GET_SUCCESS);
    }



    @Override
    public void addMoney(Integer backCardId, Double useBackMoney) {
        BmsBackCard bmsBackCard = bmsBackCardDao.findByIdAndIsOpen(backCardId,Constants.COMMON_FLAG_TRUE_INT);
        if(bmsBackCard != null){
            bmsBackCard.setCompaySet(ArithUtil.add(bmsBackCard.getCompaySet(),useBackMoney));
            bmsBackCard.setTotal(ArithUtil.add(bmsBackCard.getTotal(),useBackMoney));
            bmsBackCardDao.save(bmsBackCard);
        }
    }

    @Override
    public Map<String, Object> startMyTask(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        List<BmsDrLogic> bmsDrLogics = bmsDrLogicService.getUserTask(userId);
        BmsDrLogic bmsDrLogic;
        if(!(bmsDrLogics != null && bmsDrLogics.size() > 0)){
            bmsDrLogic = new BmsDrLogic();
            bmsDrLogic.setBmsDrOrderLogList(new ArrayList<>());
            bmsDrLogic.setUserId(userId);
            bmsDrLogic.setCompleteNum(0);
            bmsDrLogic.setStatus(Constants.COMMON_FLAG_FALSE_INT);
            bmsDrLogic.setNewTime(new Date());
            bmsDrLogicService.getBaseDao().save(bmsDrLogic);
        }else {
            bmsDrLogic = bmsDrLogics.get(0);
            List<BmsDrOrderLog> bmsDrOrderLogs = bmsDrOrderLogService.getBaseDao().findByDrLogicId(bmsDrLogic.getId());
            bmsDrLogic.setBmsDrOrderLogList(bmsDrOrderLogs);
        }
        return ResultMapHelper.success(bmsDrLogic,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public void addMoneyByUserId(Integer userId, Double useBackMoney) {
        BmsBackCard bmsBackCard = bmsBackCardDao.findByUserId(userId);
        if(bmsBackCard != null){
            bmsBackCard.setTotal((bmsBackCard.getTotal() == null ? 0 : bmsBackCard.getTotal()) + useBackMoney);
            bmsBackCardDao.save(bmsBackCard);
        }

    }
}
